import markdown2
from pathlib import Path
import tkinter as tk
from tkinter import ttk
import tempfile
import os
import webbrowser

try:
    from tkinterweb import HtmlFrame
    TKINTERWEB_AVAILABLE = True
except ImportError:
    TKINTERWEB_AVAILABLE = False
    print("警告: tkinterweb未安装，将使用简化Markdown渲染")

class MarkdownRenderer:
    def __init__(self):
        self.temp_files = []
    
    def render_markdown(self, parent, markdown_content, assets_root=None):
        """渲染Markdown内容"""
        if TKINTERWEB_AVAILABLE:
            return self._render_with_tkinterweb(parent, markdown_content, assets_root)
        else:
            return self._render_simple_fallback(parent, markdown_content)
    
    def _render_with_tkinterweb(self, parent, markdown_content, assets_root):
        """使用tkinterweb渲染Markdown（最佳效果）"""
        # 将Markdown转换为HTML
        html_content = markdown2.markdown(
            markdown_content,
            extras=['tables', 'fenced-code-blocks', 'cuddled-lists', 'code-friendly']
        )
        
        # 添加CSS样式
        styled_html = self._add_css_styles(html_content)
        
        # 创建HTML框架
        html_frame = HtmlFrame(parent, messages_enabled=False)
        html_frame.pack(fill=tk.BOTH, expand=True)
        
        # 加载HTML内容
        html_frame.load_html(styled_html)
        
        return html_frame
    
    def _render_simple_fallback(self, parent, markdown_content):
        """简化回退方案"""
        frame = ttk.Frame(parent)
        frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建文本区域显示原始Markdown
        text_frame = ttk.Frame(frame)
        text_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        text_widget = tk.Text(
            text_frame,
            wrap=tk.WORD,
            font=('Arial', 11),
            relief='flat',
            padx=10,
            pady=10
        )
        
        scrollbar = ttk.Scrollbar(text_frame, orient="vertical", command=text_widget.yview)
        text_widget.configure(yscrollcommand=scrollbar.set)
        
        text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 插入原始Markdown内容
        text_widget.insert(tk.END, markdown_content)
        text_widget.config(state=tk.DISABLED)
        
        # 添加提示
        info_label = ttk.Label(
            frame,
            text="提示: 安装 tkinterweb 可获得更好的Markdown渲染效果\npip install tkinterweb",
            foreground='blue',
            font=('Arial', 9),
            justify=tk.CENTER
        )
        info_label.pack(side=tk.BOTTOM, pady=5)
        
        return frame
    
    def _add_css_styles(self, html_content):
        """添加CSS样式美化HTML"""
        css_styles = """
        <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #ffffff;
            padding: 20px;
            margin: 0;
        }
        h1, h2, h3, h4, h5, h6 {
            color: #2c3e50;
            margin-top: 1.5em;
            margin-bottom: 0.5em;
        }
        h1 { font-size: 24px; border-bottom: 2px solid #3498db; padding-bottom: 5px; }
        h2 { font-size: 20px; border-bottom: 1px solid #bdc3c7; padding-bottom: 3px; }
        h3 { font-size: 18px; }
        p { margin-bottom: 1em; }
        strong, b { font-weight: bold; color: #e74c3c; }
        em, i { font-style: italic; }
        code {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 3px;
            padding: 2px 4px;
            font-family: 'Courier New', monospace;
            color: #e83e8c;
        }
        pre {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 15px;
            overflow-x: auto;
            margin: 1em 0;
        }
        pre code {
            background: none;
            border: none;
            padding: 0;
            color: #333;
        }
        blockquote {
            border-left: 4px solid #3498db;
            background-color: #ecf0f1;
            margin: 1em 0;
            padding: 10px 20px;
            font-style: italic;
        }
        ul, ol {
            margin: 1em 0;
            padding-left: 2em;
        }
        li {
            margin: 0.5em 0;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin: 1em 0;
        }
        th, td {
            border: 1px solid #bdc3c7;
            padding: 8px 12px;
            text-align: left;
        }
        th {
            background-color: #3498db;
            color: white;
            font-weight: bold;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        a {
            color: #2980b9;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        </style>
        """
        
        return f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            {css_styles}
        </head>
        <body>
            {html_content}
        </body>
        </html>
        """
    
    def cleanup(self):
        """清理临时文件"""
        for temp_file in self.temp_files:
            try:
                os.unlink(temp_file)
            except:
                pass
        self.temp_files.clear()